package com.bw.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bw.domain.SysUser;
import com.bw.service.SysUserService;
import com.bw.utils.common.JWTUtils;
import com.bw.utils.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author bobo棒
 * @date 2024年03月01日 11:16
 */

@RequestMapping("auth")
@RestController
public class AuthController {

    @Autowired
    SysUserService sysUserService;
    @Autowired
    RedisTemplate redisTemplate;


    @RequestMapping("login")
    public Result login(@RequestBody  SysUser sysUser){
        //校验验证码--前端输入的验证码和redis存储的验证码进行比较
        String redisCode = (String) redisTemplate.opsForValue().get(sysUser.getUid());
        if(!sysUser.getCode().equals(redisCode)){
            return Result.fail("验证码错误");
        }
        //封装查询条件--根据用户名查询数据库对象
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername,sysUser.getUsername());
        SysUser dbUser = sysUserService.getOne(wrapper);
        //查询用户名是否存在
        if(null ==dbUser){
            return Result.fail("无此账户");
        }
        //如果用户存在则比较密码是否正确
        if(!dbUser.getPassword().equals(sysUser.getPassword())){
            return Result.fail("密码错误");
        }
        //登录成功
       // 校验成功后redis处理验证码的数据
        redisTemplate.delete( sysUser.getUid());

        //创建token
        String token = JWTUtils.createToken(dbUser.getId(), 60 * 3);
        return Result.success(token);
    }

//验证码操作频繁校验
    @RequestMapping("checkCode")
    public Result checkCode(String uid){
        Long num = redisTemplate.opsForValue().increment("code" + uid, 1);
        if(num>3){
            redisTemplate.expire("code" + uid,1, TimeUnit.MINUTES);//1分钟过期
            return Result.fail("操作频繁,请稍后再试");
        }else{
            return Result.success();
        }
    }


    /***
     *
     * @param response
     * @param uid
     * @throws IOException
     */
    @RequestMapping("imageCode")
    public void createImageCode(HttpServletResponse response,String uid) throws IOException {
        //定义图形验证码的长、宽、验证码字符数、干扰元素个数
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        captcha.write(response.getOutputStream());//1.前端输出一份
        //2.后端保存一份，用于验证.默认存储2分钟
            redisTemplate.opsForValue().set(uid,captcha.getCode(),2, TimeUnit.MINUTES);
    }
}
